package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.api.SummaryApiImpl;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.admin.mapper.SummaryMapper;
import com.tanhua.admin.mapper.UserMapper;
import com.tanhua.commons.utils.DateUtils;
import com.tanhua.commons.utils.HuanBi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domain.Log;
import com.tanhua.model.domain.Summary;
import com.tanhua.model.domain.User;
import com.tanhua.model.vo.SummaryVo;
import com.tanhua.model.vo.UserComparable;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class DashboardService {

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private AnalysisMapper analysisMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SummaryMapper summaryMapper;

    @Autowired
    private SummaryApiImpl summaryApi;
    @DubboReference
    private UserApi userApi;

    //后台统计数据
    public SummaryVo summary() throws ParseException {
        String todayStr = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); //2021-08-03
        String yestodayStr = DateUtil.yesterday().toString("yyyy-MM-dd"); //工具类

        //1.调用logMapper查询所需要的数据
        Integer Usercount = userApi.selectCount();
        Integer numRegister = logMapper.queryByTypeAndLogTime("0102", todayStr);
        Integer numRegistered = logMapper.queryByTypeAndLogTime("0102", yestodayStr);
        Integer numLogin = logMapper.queryByTypeAndLogTime("0101", todayStr);
        Integer numLogined = logMapper.queryByTypeAndLogTime("0101", yestodayStr);
        Integer numActived = logMapper.queryByLogTime(yestodayStr);
        Integer numActive = logMapper.queryByLogTime(todayStr);
        //2.调用analysisMapper查询所需要的数据
        List<Integer> sevenList = analysisMapper.queryNumWeekActive(DateUtils.getRanmdomDaysAgo(7));
        List<Integer> thirtyList = analysisMapper.queryNumMonthActive(DateUtils.getRanmdomDaysAgo(30));
        Integer Active_During_OneWeek = 0;
        Integer Active_During_OneMonth = 0;
        for (Integer singleDay : sevenList) {
            Active_During_OneWeek+=singleDay;
        }
        for (Integer singleDay : thirtyList) {
            Active_During_OneMonth+=singleDay;
        }

        //3.根据record_date查询summary表中是否有今日的统计数据
        Date recordDate = new SimpleDateFormat("yyyy-MM-dd").parse(todayStr);
        QueryWrapper<Summary> qw1 = new QueryWrapper<>();
        qw1.eq("record_date", recordDate);
        Summary summary = summaryMapper.selectOne(qw1);
        //4.判断是否存在
          //4.1数据存在（更新）
        if (summary != null) {
            summary.setActivePassMonth(Active_During_OneMonth);
            summary.setActivePassWeek(Active_During_OneWeek);
            summary.setActiveUsersToday(numActive);
            summary.setCumulativeUsers(Usercount);
            summary.setLoginTimesToday(numLogin);
            summary.setNewUsersToday(numRegister);
            Double activeUsersTodayRate = HuanBi.computeRate(numActive,numActived);
            Double loginTimesTodayRate = HuanBi.computeRate(numLogin, numLogined);
            Double newUsersTodayRate =HuanBi.computeRate(numRegister,numRegistered);
            summary.setActiveUsersTodayRate(activeUsersTodayRate);
            summary.setLoginTimesTodayRate(loginTimesTodayRate);
            summary.setNewUsersTodayRate(newUsersTodayRate);
            summaryMapper.updateById(summary);
        } else {
            //4.2数据不存在（保存）
            summary = new Summary();
            summary.setActivePassMonth(Active_During_OneMonth);
            summary.setActivePassWeek(Active_During_OneWeek);
            summary.setActiveUsersToday(numActive);
            summary.setCumulativeUsers(Usercount);
            summary.setLoginTimesToday(numLogin);
            summary.setNewUsersToday(numRegister);
            summary.setRecordDate(recordDate);
            Double activeUsersTodayRate = HuanBi.computeRate(numActive,numActived);
            Double loginTimesTodayRate = HuanBi.computeRate(numLogin, numLogined);
            Double newUsersTodayRate = HuanBi.computeRate(numRegister,numRegistered);
            summaryMapper.insert(summary);
        }
        //5.数据封装Vo返回
        Summary summary1 = summaryMapper.selectById(summary.getId());
        SummaryVo vo = new SummaryVo();
        vo.setActivePassMonth(summary1.getActivePassMonth());
        vo.setActivePassWeek(summary1.getActivePassWeek());
        vo.setActiveUsersToday(summary1.getActiveUsersToday());
        vo.setCumulativeUsers(summary1.getCumulativeUsers());
        vo.setLoginTimesToday(summary1.getLoginTimesToday());
        vo.setNewUsersToday(summary1.getNewUsersToday());
        vo.setActiveUsersTodayRate(summary1.getActiveUsersTodayRate());
        vo.setLoginTimesTodayRate(summary1.getLoginTimesTodayRate());
        vo.setNewUsersTodayRate(summary1.getNewUsersTodayRate());
        return vo;
    }



    //新增，活跃，次日留存
    public UserComparable user(String sd, String ed, String type) {
        if (type.equals("101")) {
            UserComparable register = summaryApi.numRegister(sd, ed);
            return register;
        } else if (type.equals("102")) {
            return summaryApi.numActive(sd, ed);
        } else if (type.equals("103")) {
            return summaryApi.numRetention1d(sd, ed);
        }
        return new UserComparable(null,null);
    }
}


